package com.think.teaching.utils.service;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Enumeration;
import java.util.Queue;
import java.util.concurrent.LinkedBlockingQueue;

import org.apache.tools.zip.ZipEntry;
import org.apache.tools.zip.ZipFile;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.PutObjectRequest;
import com.think.teaching.utils.controller.FileUploadController;

@Component
public class FileUploadService {


	// yourEndpoint填写Bucket所在地域对应的Endpoint。以华东1（杭州）为例，Endpoint填写为https://oss-cn-hangzhou.aliyuncs.com。
	@Value("${oss.endpoint}")
	String endpoint;
	// 阿里云账号AccessKey拥有所有API的访问权限，风险很高。强烈建议您创建并使用RAM用户进行API访问或日常运维，请登录RAM控制台创建RAM用户。
	@Value("${oss.accessKeyId}")
	String accessKeyId;
	@Value("${oss.accessKeySecret}")
	String accessKeySecret;
	@Value("${oss.bucket}")
	String bucketName;
	
	public FileUploadService() {
				
	}
	
	private void proccessTask() {
		new Thread(new Runnable() {
			
			@Override
			public void run() {
				// TODO Auto-generated method stub
				while (true) {
					OssFileTask task = tasks.poll();
					
					if (task == null) {
						
					}
					else {
						System.out.println(task.uploadPath);
						ossUploadFiles(task.file,task.uploadPath);
					}
					try {
						Thread.sleep(500);
					} catch (InterruptedException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
			}
		}).start();
	}
	public static void unZip(File zipFile, String outDir) throws IOException {

		File outFileDir = new File(outDir);
		if (!outFileDir.exists()) {
			boolean isMakDir = outFileDir.mkdirs();
			if (!isMakDir) {
				throw new IOException("创建文件夹失败");
			}
		}

		ZipFile zip = new ZipFile(zipFile);
		for (Enumeration enumeration = zip.getEntries(); enumeration.hasMoreElements();) {
			ZipEntry entry = (ZipEntry) enumeration.nextElement();
			String zipEntryName = entry.getName();
			InputStream in = zip.getInputStream(entry);

			if (entry.isDirectory()) { // 处理压缩文件包含文件夹的情况
				File fileDir = new File(outDir + zipEntryName);
				fileDir.mkdir();
				continue;
			}

			File file = new File(outDir, zipEntryName);
			file.createNewFile();
			OutputStream out = new FileOutputStream(file);
			byte[] buff = new byte[1024];
			int len;
			while ((len = in.read(buff)) > 0) {
				out.write(buff, 0, len);
			}
			in.close();
			out.close();
		}
		zip.close();
		
	}
	private class OssFileTask{
		public String path;
		
		public File file;
		
		public String uploadPath;
	}
	
	private Queue<OssFileTask> tasks = new LinkedBlockingQueue<FileUploadService.OssFileTask>();
	public void UploadZip(String destpath,String originFileName) throws IOException {
		String basePath = "E:/fileUpload/" + "unzips/";
		
		String coursePath = "testSchool/testCollege/testmajor/testCourse";

		File dest = new File(destpath);
		unZip(dest, destpath.substring(0, destpath.length() - 4) + "/");
		File[] files = new File(destpath.substring(0, destpath.length() - 4)).listFiles();
		
		for (int i = 0; i < files.length; i++) {
			if (!files[i].isDirectory()) {
				OssFileTask task = new OssFileTask();
				task.file =files[i];
				task.path = files[i].getAbsolutePath();
				task.uploadPath =String.format("%s/%s/%s", coursePath,originFileName,files[i].getName());
				tasks.add(task);
			}
		}
		proccessTask();

	}
	
	public boolean ossUploadFiles(File file,String dstPath) {
		// 创建OSSClient的实例
		OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
		try {
			InputStream multipartFileInputStream = new FileInputStream(file);
			PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, dstPath,
					multipartFileInputStream);
			ossClient.putObject(putObjectRequest);
			ossClient.shutdown();

		} catch (IOException e) {
			e.printStackTrace();
			ossClient.shutdown();
			return false;
		} finally {
			// 关闭流
		}
		return true;
	}

}
